// https://leetcode.cn/problems/set-matrix-zeroes/description/?envType=study-plan-v2&envId=top-100-liked

// 较优解
class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int col = matrix[0].size();
        int row = matrix.size();
        bool x = false, y = false;
        for(int i = 0; i < row; i++) {
            if(matrix[i][0] == 0)
                x = true;
        }
        for(int i = 0; i < col; i++) {
            if(matrix[0][i] == 0)
                y = true;
        }

        for (int i = 1; i < row; i++) {
            for (int j = 1; j < col; j++) {
                if (matrix[i][j] == 0) {
                    matrix[0][j] = 0;
                    matrix[i][0] = 0;
                }
            }
        }
        for (int i = 1; i < row; i++) {
            if (matrix[i][0] == 0) {
                for (int j = 1; j < col; j++) {
                    matrix[i][j] = 0;
                }
            }
        }
        for (int j = 1; j < col; j++) {
            if(matrix[0][j] == 0)
            for (int i = 1; i < row; i++) {
                matrix[i][j] = 0;
            }
        }
        if(x) {
            for(int i = 0; i < row; i++) {
                matrix[i][0] = 0;
            }
        }
        if(y) {
            for(int i = 0; i < col; i++) {
                matrix[0][i] = 0;
            }
        }
    }
};


// 最优解
class Solution {
public:
    void setZeroes(vector<vector<int>>& matrix) {
        int m = matrix.size();
        int n = matrix[0].size();
        int flag_col0 = false;
        for (int i = 0; i < m; i++) {
            if (!matrix[i][0]) {
                flag_col0 = true;
            }
            for (int j = 1; j < n; j++) {
                if (!matrix[i][j]) {
                    matrix[i][0] = matrix[0][j] = 0;
                }
            }
        }
        for (int i = m - 1; i >= 0; i--) {
            for (int j = 1; j < n; j++) {
                if (!matrix[i][0] || !matrix[0][j]) {
                    matrix[i][j] = 0;
                }
            }
            if (flag_col0) {
                matrix[i][0] = 0;
            }
        }
    }
};
